package com.neptune.imapp.ui.compose.screen.frontPage.login

import android.content.res.Configuration
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusManager
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.platform.SoftwareKeyboardController
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavController
import androidx.navigation.compose.rememberNavController
import com.neptune.imapp.R
import com.neptune.imapp.ui.compose.navigation.RouterConfig
import com.neptune.imapp.ui.compose.screen.frontPage.FrontPageViewModel
import com.neptune.imapp.ui.theme.AppTheme
import com.neptune.imapp.utils.RegexUtil

@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun Login(
    viewModel: FrontPageViewModel,
    navController: NavController
) {
    val keyboardController = LocalSoftwareKeyboardController.current
    val focusManager = LocalFocusManager.current
    Column(modifier = Modifier.autoCloseKeyboard(keyboardController, focusManager)) {
        Icon(
            painter = painterResource(id = R.drawable.logo),
            contentDescription = null,
            modifier = Modifier
                .align(Alignment.CenterHorizontally)
                .size(200.dp)
                .padding(top = 30.dp),
            tint = MaterialTheme.colorScheme.primary
        )
        LoginForm(viewModel = viewModel, navController)
        Spacer(modifier = Modifier.height(50.dp))
        Text(
            text = "Forget Your Password?",
            modifier = Modifier
                .padding(horizontal = 10.dp, vertical = 20.dp)
                .clickable(interactionSource = MutableInteractionSource(), indication = null) {
                    navController.navigate(RouterConfig.ROUTE_Help)
                },
            fontSize = 15.sp,
            fontFamily = FontFamily.Serif,
        )
        Text(
            text = "Register",
            modifier = Modifier
                .align(Alignment.End)
                .padding(horizontal = 10.dp)
                .clickable(interactionSource = MutableInteractionSource(), indication = null) {
                    navController.navigate(RouterConfig.ROUTE_Register)
                },
            fontSize = 15.sp,
            fontFamily = FontFamily.Serif
        )
    }
}

@OptIn(ExperimentalLayoutApi::class)
@Composable
fun LoginForm(viewModel: FrontPageViewModel, navController: NavController) {
    val insets = WindowInsets.ime
    Column(
        verticalArrangement = Arrangement.spacedBy(20.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
        modifier = Modifier
            .padding(start = 20.dp, end = 20.dp, top = 40.dp)
            .consumedWindowInsets(insets)
    ) {
        val localFocusManager = LocalFocusManager.current
        val focusRequester = FocusRequester()
        InputTextField(
            bindValue = viewModel.phoneVal,
            label = "PhoneNumber",
            placeholder = "Please Input your Phone",
            leadingIcon = {
                IconButton(
                    content = {
                        Icon(
                            painter = painterResource(R.drawable.ic_lock),
                            contentDescription = null
                        )
                    },
                    onClick = {
                    }
                )
            },
            trailingIcon = {
                IconButton(
                    content = {
                        Icon(
                            painter = painterResource(R.drawable.ic_delete),
                            contentDescription = null
                        )
                    },
                    enabled = viewModel.phoneVal.value.isNotEmpty(),
                    onClick = {
                        viewModel.clearString(viewModel.phoneVal)
                    }
                )
            },
            modifier = Modifier
                .fillMaxWidth()
                .onFocusChanged {
                    viewModel.phoneError.value = RegexUtil.checkPhoneNumber(viewModel.phoneVal)
                },
            isError = viewModel.phoneError.value,
            imeAction = ImeAction.Next
        )
        InputTextField(
            bindValue = viewModel.passwordVal,
            label = "Password",
            placeholder = "Please Input your Password",
            leadingIcon = {
                IconButton(
                    content = {
                        Icon(
                            painter = painterResource(if (viewModel.passwordVisibility.value) R.drawable.ic_invisible else R.drawable.ic_visible),
                            contentDescription = null
                        )
                    },
                    onClick = {
                        viewModel.passwordInputClick()
                    }
                )
            },
            trailingIcon = {
                IconButton(
                    content = {
                        Icon(
                            painter = painterResource(R.drawable.ic_delete),
                            contentDescription = null
                        )
                    },
                    enabled = viewModel.passwordVal.value.isNotEmpty(),
                    onClick = {
                        viewModel.clearString(viewModel.passwordVal)
                    }
                )
            },
            modifier = Modifier
                .fillMaxWidth(),
            visualTransformation = if (viewModel.passwordVisibility.value) PasswordVisualTransformation() else VisualTransformation.None,
            keyboardActions = KeyboardActions(onDone = {
                localFocusManager.clearFocus()
                focusRequester.requestFocus()
            }), imeAction = ImeAction.Done,
            isError = viewModel.passwordError.value
        )
        AnimatedVisibility(visible = viewModel.phoneError.value || viewModel.passwordError.value) {
            Snackbar(action = {
                Button(onClick = {
                    if (viewModel.phoneError.value) viewModel.phoneError.value =
                        false else viewModel.passwordError.value = false
                }) {
                    Text(text = "关闭")
                }
            }) {
                Text(text = viewModel.errorMessage.value)
            }
        }
        Button(
            content = {
                Text(
                    text = "Login",
                    fontSize = 20.sp,
                    fontStyle = FontStyle.Italic
                )
            },
            onClick = {
                viewModel.login(navController)
            },
            enabled = !viewModel.isPhoneError.value && viewModel.passwordVal.value.isNotEmpty() && viewModel.phoneVal.value.isNotEmpty(),
            modifier = Modifier
                .size(100.dp, 50.dp)
                .focusRequester(focusRequester),
            shape = RoundedCornerShape(5.dp),
            elevation = ButtonDefaults.elevatedButtonElevation(10.dp, 0.dp, 5.dp)
        )
    }
}

@OptIn(ExperimentalComposeUiApi::class)
fun Modifier.autoCloseKeyboard(
    keyboardController: SoftwareKeyboardController?,
    focusManager: FocusManager
): Modifier =
    pointerInput(this) {
        detectTapGestures(
            onPress = {
                keyboardController?.hide()
                focusManager.clearFocus()
            }
        )
    }

@Composable
fun InputTextField(
    bindValue: MutableState<String>,
    label: String,
    placeholder: String,
    leadingIcon: @Composable (() -> Unit)? = null,
    trailingIcon: @Composable (() -> Unit)? = null,
    modifier: Modifier,
    visualTransformation: VisualTransformation = VisualTransformation.None,
    isError: Boolean = false,
    keyboardActions: KeyboardActions = KeyboardActions.Default,
    imeAction: ImeAction
) {
    OutlinedTextField(
        value = bindValue.value,
        onValueChange = { bindValue.value = it },
        label = { Text(label, fontFamily = FontFamily.Serif, fontSize = 15.sp) },
        placeholder = { Text(placeholder, fontFamily = FontFamily.Serif, fontSize = 13.sp) },
        singleLine = true,
        keyboardOptions = KeyboardOptions(
            keyboardType = KeyboardType.Password,
            imeAction = imeAction
        ),
        keyboardActions = keyboardActions,
        visualTransformation = visualTransformation,
        leadingIcon = leadingIcon,
        trailingIcon = trailingIcon,
        shape = RoundedCornerShape(10.dp),
        modifier = Modifier
            .then(modifier),
        isError = isError
    )
}

@Preview(showBackground = true, uiMode = Configuration.UI_MODE_NIGHT_YES)
@Composable
fun LoginDayLight() {
    AppTheme {
        Surface(
            modifier = Modifier.fillMaxSize(),
            color = MaterialTheme.colorScheme.background
        ) {
            Login(viewModel = FrontPageViewModel(), navController = rememberNavController())
        }
    }
}

@Preview(showBackground = true, uiMode = Configuration.UI_MODE_NIGHT_NO)
@Composable
fun LoginNight() {
    AppTheme {
        Surface(
            modifier = Modifier.fillMaxSize(),
            color = MaterialTheme.colorScheme.background
        ) {
            Login(viewModel = FrontPageViewModel(), navController = rememberNavController())
        }
    }
}